const { Op, where } = require("sequelize");
const sequelize = appRequire('db');
var COS = require('cos-nodejs-sdk-v5');
const posterModel = appRequire('models/poster');
const thisRequest = require('sync-request');
const userModel = appRequire('models/user');
const path = require('path');
const fs = require('fs');

// 导出对象，供其它模块调用
module.exports = {
    detail,
    type,
    tagList,
    posterList,
    fontList,
    materialTagList,
    materialList,
    assemblyList,
    assemblyDet,
    findUserPoster,
    createUserPoster,
    opus,
};


async function opus(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    //console.log(postData)
    url = "https://poster.miaogeban.com/poster/opus"
    var res = thisRequest('PUT', url, {
        json:  postData,
        headers: {
            Authorization: Authorization
        }
    });
    var body = res.getBody();
    var jsonObj = JSON.parse(body); // 解析接口返回的JSON内容
    jsonObj.code = 1
    request.json(jsonObj)
}

//组件详情
async function assemblyDet(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    url = "https://poster.miaogeban.com/poster/assembly/" + postData.objectId
    var res = thisRequest('GET', url, {
        json: {},
        headers: {
        }
    });
    var body = res.getBody();
    var jsonObj = JSON.parse(body); // 解析接口返回的JSON内容
    jsonObj.code = 1
    request.json(jsonObj)
}

//组件列表
async function assemblyList(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    url = "https://poster.miaogeban.com/poster/assembly/list?pageNum=" + postData.pageNum +
        "&pageSize=" + postData.pageSize + "&sizeId=&typeId=" + postData.typeId + "&columnNum=" + postData.columnNum
    var res = thisRequest('GET', url, {
        json: {},
        headers: {
        }
    });
    var body = res.getBody();
    var jsonObj = JSON.parse(body); // 解析接口返回的JSON内容
    jsonObj.code = 1
    request.json(jsonObj)
}

//插画的tag
async function materialTagList(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    url = "https://poster.miaogeban.com/poster/materialBackdrop/materialTagList?typeId=" + postData.typeId
    var res = thisRequest('GET', url, {
        json: {},
        headers: {
        }
    });
    var body = res.getBody();
    var jsonObj = JSON.parse(body); // 解析接口返回的JSON内容
    jsonObj.code = 1
    request.json(jsonObj)
}

//插画列表
async function materialList(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    url = "https://poster.miaogeban.com/poster/materialBackdrop/materialList?pageNum=" + postData.pageNum +
        "&pageSize=" + postData.pageSize + "&sizeId=&typeId=" + postData.typeId + "&tagId=" + postData.tagId
    var res = thisRequest('GET', url, {
        json: {},
        headers: {
        }
    });
    var body = res.getBody();
    var jsonObj = JSON.parse(body); // 解析接口返回的JSON内容
    jsonObj.code = 1
    request.json(jsonObj)
}


async function fontList(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    /*let result1 = Common.checkUrl(postData, ['uid'], request);
    if (result1 == false) return;*/

    let result = await posterModel.fonts.findAll({
    });

    result = Common.clone(result)
    returnData.data = result

    return request.json(returnData)
}


//获取当前海报列表
async function posterList(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let url = "https://poster.miaogeban.com/poster/tag/templates??pageSize=" + postData.pageSize + "&pageNum=" + postData.pageNum + "&rid=" + postData.rid + "&tagId=" + postData.tagId + "&type=1"

    var res = thisRequest('GET', url, {
    });
    var body = res.getBody();
    var jsonObj = JSON.parse(body); // 解析接口返回的JSON内容

    returnData.maxCount = jsonObj.data.total
    returnData.maxPage = Math.ceil(jsonObj.data.total / postData.pageSize)
    returnData.data = jsonObj.data.rows
    return request.json(returnData)
}

async function type(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    /*let result1 = Common.checkUrl(postData, ['uid'], request);
    if (result1 == false) return;*/

    let result = await posterModel.postType.findAll({
        order: [['id', 'ASC']]
    });

    result = Common.clone(result).sort((a, b) => { return Number(a.id) - Number(b.id) })

    for (let item1 of result) {
        for (let item2 of item1.bclazzs) {
            if (item2.name == "课程表") item2.isHot = true
        }
    }

    returnData.data = result

    return request.json(returnData)
}

async function tagList(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    /*let result1 = Common.checkUrl(postData, ['uid'], request);
    if (result1 == false) return;*/

    let url = "https://poster.miaogeban.com/poster/realm?id=" + postData.id + "&type=1"

    console.log(url)

    var res = thisRequest('GET', url, {
    });
    var body = res.getBody();
    var jsonObj = JSON.parse(body); // 解析接口返回的JSON内容
    console.log(jsonObj)
    jsonObj.code = 1

    /*let result = await posterModel.postTag.findOne({
        where: {
            id: postData.id
        }
    });

    result = Common.clone(result)
    returnData.data = result*/

    return request.json(jsonObj)
}

async function detail(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    /*let result1 = Common.checkUrl(postData, ['uid'], request);
    if (result1 == false) return;*/

    let url = "https://poster.miaogeban.com/poster/template/" + postData.objectId

    var res = thisRequest('GET', url, {
        headers: {
            Authorization: Authorization
        }
    });
    var body = res.getBody();
    var jsonObj = JSON.parse(body); // 解析接口返回的JSON内容
    console.log(jsonObj)
    jsonObj.code = 1
    /*let result = await posterModel.poster.findOne({
        where: {
            id: postData.objectId
        }
    });
    result = Common.clone(result)

    returnData.data = result*/

    return request.json(jsonObj)
}

async function findUserPoster(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    /*let checkResult = Common.checkUrl(postData, ['uid'], request);
    if (checkResult == false) return;*/

    let result = await posterModel.userPoster.findOne({
        where: {
            id: postData.id,
            //parent: postData.uid
        }
    });

    returnData.data = Common.clone(result)
    return request.json(returnData)
}

//生成海报
async function createUserPoster(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let thisUser = await userModel.user.findOne({
        where: {
            objectId: postData.uid
        }
    })
    let result = await posterModel.userPoster.count({
        parent: postData.uid
    });

    thisUser = Common.clone(thisUser)
    if ((thisUser && thisUser.vipTime) || result == 0) { //已是会员
        let result = await posterModel.userPoster.create({
            id: sid.uuid(),
            posterId: postData.posterId,
            dragBg: postData.dragBg,
            dragList: postData.dragList,
            parent: postData.uid
        });
        result = Common.clone(result)

        returnData.data = "https://artapi.jimuzhou.cloud/" + imgUrl
    } else {
        returnData.code = 103
        returnData.msg = "目前此功能仅限会员使用"
    }

    request.json(returnData)
}

async function screenshotDOMElement(page, selector, path, padding = 0) {
    const rect = await page.evaluate(selector => {
        try {
            const element = document.querySelector(selector);
            const { x, y, width, height } = element.getBoundingClientRect();
            if (width * height != 0) {
                return { left: x, top: y, width, height, id: element.id };
            } else {
                return null;
            }
        } catch (e) {
            return null;
        }
    }, selector);

    return await page.screenshot({
        path: path,
        clip: rect ? {
            x: rect.left - padding,
            y: rect.top - padding,
            width: rect.width + padding * 2,
            height: rect.height + padding * 2
        } : null
    });
}
